<?php

namespace App\Http\Controllers\Wechat;


use App\Model\System\User;
use App\Model\Wechat\WechatUser;

class AuthorizeController extends HelpController
{



    /**
     * 用户授权访问页面
     */
    public function authorize($url)
    {
        try {
            $app = $this->app;
            $app['config']->set('oauth.callback','/wechat/redirect/'.$url);
            $oauth = $app->oauth;
            $response = $oauth->scopes(['snsapi_base'])
                    ->redirect();
            return $response;

        }catch (\Exception $e){
            return $this->fail(false,'授权失败'.$e->getMessage());
        }


    }

    /**
     * 重定向页面
     * @return array
     * @throws \Exception
     *
     */

    public function redirect($url)
    {
        try{
            $oauth = $this->app->oauth;
            // 获取 OAuth 授权结果用户信息
            $user = $oauth->user();
            app('session')->put('openid',$user->id);
            app('session')->put('url',$url);
            // 检测是否绑定过此用户
            $wechatuser = WechatUser::where('openid',$user->id)->first();
            if(empty($wechatuser)){
                return redirect('home/login_m_new.html');
            }else{
                return redirect('home/redirect.html');
            }
        }catch (\Exception $e){
            return $this->fail(false,'跳转失败'.$e->getMessage());
        }
    }

}
